function randomStr(n) { // 生成n位长度的字符串
  var str = "abcdefghijklmnopqrstuvwxyz0123456789"; // 可以作为常量放到random外面
  var result = "";
  for(let i = 0; i < n; i++) {
    result += str[parseInt(Math.random() * str.length)];
  }
  return result;
}
function loadJS(url, callback,callbackErr ){//动态引入js
  var script = document.createElement('script'),fn = callback || function(){},errfn = callbackErr || function(){};
  script.type = 'text/javascript';
  //IE
  if(script.readyState){
    script.onreadystatechange = function(){
      if( script.readyState == 'loaded' || script.readyState == 'complete' ){
        script.onreadystatechange = null;
        fn();
      }else{
        errfn();
      }
    };
  }else{
    //其他浏览器
    script.onload = function(){
      fn();
    };
    script.onerror = function(){
      errfn();
    }
  }
  script.src = url;
  document.getElementsByTagName('head')[0].appendChild(script);
}
function loadStyles(url){//动态引入css
  var link = document.createElement("link");
  link.rel = "stylesheet";
  link.type = "text/css";
  link.href = url;
  var head = document.getElementsByTagName("head")[0];
  head.appendChild(link);
}
function formatTime(date, fmt="yyyy-MM-dd HH:mm:ss"){//时间格式过滤器
  if(!date){
    return "";
  }
  if(typeof date == "string"&&/^\d+$/.test(date)){
    date = parseInt(date);
  }
	date = new Date(date);
	// 返回处理后的值
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
	}
	let o = {
		'M+': date.getMonth() + 1,
		'd+': date.getDate(),
		'h+': date.getHours(),
		'H+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds()
	}
	for (let k in o) {
		if (new RegExp(`(${k})`).test(fmt)) {
			let str = o[k] + ''
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length))
		}
	}
	return fmt
}
function date_format(timestramp){//"210524165408"=>"2021-05-24 16:54:08"
  if(!timestramp){
    return "";
  }else if(!!timestramp&&timestramp.length != 12){
    return timestramp;
  }
  var year = "20"+timestramp.substr(0,2);
  var month = timestramp.substr(2,2);
  var day = timestramp.substr(4,2);
  var hour = timestramp.substr(6,2);
  var minute = timestramp.substr(8,2);
  var second = timestramp.substr(10,2);
  return year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second;
}
function tranlateTime(val){//转换秒的显示-->>>n天n时n分n秒
  let result = ""
  function setStr(time){
    if(time>=60*60*24){//天
      result += parseInt(time/(60*60*24)) + "day";
      time = time%(60*60*24);
      setStr(time);
    }else if(time>=60*60&&time<60*60*24){//时
      result += parseInt(time/(60*60)) + "h";
      time = time%(60*60);
      setStr(time);
    }else if(time>=60&&time<60*60){//分
      result += parseInt(time/60) + "m";
      time = time%60;
      setStr(time);
    }else if(time>0&&time<60){//秒
      result += time + "s";
    }
  }
  if(!val){
    result = (val||0) + "s";
  }else{
    setStr(val);
  }
  return result;
}
//判断浏览器类型
function myBrowser(){
  var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  var isOpera = userAgent.indexOf("Opera") > -1;
  if (isOpera) {
      return "Opera"
  }; //判断是否Opera浏览器
  if (userAgent.indexOf("Firefox") > -1) {
      return "FF";
  } //判断是否Firefox浏览器
  if (userAgent.indexOf("Chrome") > -1){
      return "Chrome";
  }
  if (userAgent.indexOf("Safari") > -1) {
      return "Safari";
  } //判断是否Safari浏览器
  if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
      return "IE";
  }; //判断是否IE浏览器
  if (userAgent.indexOf("Trident") > -1) {
      return "Edge";
  } //判断是否Edge浏览器
}
//IE浏览器图片保存本地
function SaveAs5(imgURL,fileName){
  var oPop = window.open(imgURL,"","width=1, height=1, top=5000, left=5000");
  for(; oPop.document.readyState != "complete"; )
  {
      if (oPop.document.readyState == "complete")break;
  }
  oPop.document.execCommand("SaveAs");
  oPop.close();
}
//谷歌，360极速等浏览器下载
function download(src,fileName) {
  var $a = document.createElement('a');
  $a.setAttribute("href", src);
  $a.setAttribute("download", fileName);
  var evObj = document.createEvent('MouseEvents');
  evObj.initMouseEvent( 'click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
  $a.dispatchEvent(evObj);
  setTimeout(() => {
    document.body.removeChild($a);
  }, 1000);
};
//火狐等浏览器下载
function firefoxSave(src,fileName) {
  var id = new Date().getTime();
  var a = '<a href="'+src+'" download="'+fileName+'" id="'+id+'" ></a>';
  $('body').append($(a));
  document.getElementById(id).click();
  setTimeout(() => {
    $(a).remove();
  }, 1000);
};
//多浏览器图片下载
function toDownLoadImg(url,fileName) {
  if(myBrowser()==="IE"||myBrowser()==="Edge"){
    SaveAs5(url,fileName);
  }else if(myBrowser()==="FF"){
    firefoxSave(url,fileName);
  }else{
    download(url,fileName);
  }
}
function compareObj() {//对讲数组按arg降序排列
  let sort1 = arguments[0],sort2 = arguments[1];
  //arguments目前支持的是第一位是carstatus，第二位支持的是车牌号name(先字母升序，再汉字，最后数字升序)
  return function(a, b) {
    if(a.nodetype!=b.nodetype||a.nodetype==1||b.nodetype==1){
      return 0;
    }else{
      if ((b[sort1]===a[sort1]||(b[sort1]>2&&a[sort1]>2))&&sort2) {// 第一顺位相同时，找第2顺位
        let firstB = parseFloat(b[sort2]);
        if(isNaN(firstB)){
          firstB = b[sort2].split("")[0];
        }
        let firstA = parseFloat(a[sort2]);
        if(isNaN(firstA)){
          firstA = a[sort2].split("")[0];
        }
        if(firstB>firstA){
          return -1;
        }else if(firstB<firstA){
          return 1;
        }else{
          return 0;
        }
      } else {
        return b[sort1] - a[sort1];
      }
    }
  }
}
export default {
  randomStr: randomStr,
  loadJS: loadJS,
  loadStyles: loadStyles,
  formatTime: formatTime,
  date_format: date_format,
  tranlateTime: tranlateTime,
  toDownLoadImg: toDownLoadImg,
  compareObj: compareObj,
};